<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BunnySpell</title>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Fredoka&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='game.css') }}">
</head>
<body>

    <!-- 在 body 标签的开始处添加这行 -->
    <div id="blur-overlay"></div>

    
    <div id="logo" class="logo-container">
        <a href="{{ url_for('home') }}" class="logo-link">
            <img src="{{ url_for('static', filename='bunnyspell.png') }}" alt="Logo" class="logo-img">
            <span class="logo-text">BunnySpell</span>
        </a>
    </div>

      <!-- 新增：中间的按钮 -->
        <div class="header-buttons">
            {% if current_user.is_authenticated %}
                {% if current_user.role == 'parent' %}
                    <a href="{{ url_for('game_creator') }}" class="header-button">+ Game</a>
                {% endif %}
                <a href="{{ url_for('game') }}" class="header-button">Play</a>
                <a href="{{ url_for('profile') }}" class="header-button">Profile</a>
            {% endif %}
        </div>

    <h1 class="game-title">{{ game_title }}</h1>
    {% if current_user.is_authenticated %}
    <div class="user-info">
        <span class="username">Welcome, {{ current_user.username }}</span>
        <a href="{{ url_for('logout') }}" class="logout-button" title="Logout">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                <polyline points="16 17 21 12 16 7"></polyline>
                <line x1="21" y1="12" x2="9" y2="12"></line>
            </svg>
        </a>
    </div>
    {% endif %}
    <div id="score">Score: 0</div>
    <div id="aichat-container">
    </div>
    <div class="game-content">
        <div id="word-display">HELLO</div>
        <div id="input-container"></div>
        <!-- Add the SKIP button here -->
        <button id="skip-button" class="skip-button">SKIP</button>
        <div id="combo-display">Combo x0</div>
    </div>
    <div id="wordlist-container" style="display: none;">
        <div class="wordlist-column">
            <ul id="word-results"></ul>
        </div>
    </div>
    <div id="final-score"></div>
    <div id="timer-container">
        <div id="timer"></div>
    </div>
    <div id="times-up" class="times-up">TIME'S UP!</div>
    <!-- Add this new element for the completion image -->
    <div id="completion-image" class="completion-image"></div>
    <button id="start-game-button" onclick="startGame()">Start Game</button>
    <script>
        // 使用 Jinja2 将 word_dict 渲染到前端
        const wordDictionary = JSON.parse('{{ word_dict | tojson | safe }}');
        const game_id = '{{ game_id }}';
        // 从 wordDictionary 中获取所有单词
        const words = Object.keys(wordDictionary);

        console.log(wordDictionary);
        console.log(words);
 
        const wordDisplay = document.getElementById("word-display");
        const inputContainer = document.getElementById("input-container");
        const scoreDisplay = document.getElementById("score");
        const comboDisplay = document.getElementById("combo-display");
        const timerDuration =  words.length * {{ game_spell_speed }}; // Use the game_spell_speed passed from the server
        let timer = timerDuration;
        let score = 0;
        let wordIndex = 0;
        let combo = 0;

        // 初始化单词
        let totalAttempts = 0;
        let correctAttempts = 0;

        let currentWord = '';
        let correctLetters = [];  // 新增：用于跟踪已正确输入的字母

        let wordResults = {};
        let completionRate = 0;
        let completedWords = 0;  // New variable to track completed words

        let autoPlayEnabled = false;

        // 修改 playAudioTwice 函数
        function playAudioTwice(audioUrl) {
            const audio = new Audio(audioUrl);
            let playCount = 0;

            // 获取当前单词的音频图标元素
            const iconElement = document.querySelector('.audio-icon');

            function playWithAnimation() {
                iconElement.classList.add('playing');
                
                audio.play().catch(error => console.log("Playback prevented:", error));
                
                audio.onended = function() {
                    iconElement.classList.remove('playing');
                    playCount++;
                    if (playCount < 2) {
                        setTimeout(playWithAnimation, 1000); // 1秒后播放第二次
                    }
                };
            }

            playWithAnimation();
        }

        function initializeWord() {
            if (wordIndex >= words.length) {
                // 在这里添加额外的分数
                score += combo * 2;
                
                // 计算剩余时间并加入得分
                const remainingTime = timeLeft;
                const additionalScore = remainingTime * 10;
                score += additionalScore;
                completionRate = (completedWords / words.length).toFixed(2);
                scoreDisplay.innerText = `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
                endGame();
                return;
            }
            
            // 在开始新单词之前，添加额外的分数（除了第一个单词）
            if (wordIndex > 0) {
                score += combo * 2;
                completionRate = (completedWords / words.length).toFixed(2);
                scoreDisplay.innerText = `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
            }
            
            combo = 0;
            displayCombo();
            inputContainer.innerHTML = "";
            currentWord = words[wordIndex];
            correctLetters = new Array(currentWord.length).fill(false);
            
            // 初始化单词结果为未完成
            wordResults[currentWord] = false;
            
            // 显示单词的含义和例句
            wordDisplay.innerHTML = `
                <div class="word-meaning">
                    ${wordDictionary[currentWord].meaning} 
                    <span class="word-phonetic">
                        (${wordDictionary[currentWord].pronunciation})
                        <span class="audio-icon" onclick="playAudio('${wordDictionary[currentWord].audio}', this)">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" class="speaker"></polygon>
                                <path d="M15.54 8.46a5 5 0 0 1 0 7.07" class="wave1"></path>
                                <path d="M19.07 4.93a10 10 0 0 1 0 14.14" class="wave2"></path>
                            </svg>
                        </span>
                    </span>
                </div>
                <div class="word-example">${wordDictionary[currentWord].example.replace(currentWord, '[ ]')}</div>
            `;

            // 只有在启用自动播放后才自动播放读音
            if (autoPlayEnabled && wordDictionary[currentWord].audio) {
                setTimeout(() => {
                    playAudioTwice(wordDictionary[currentWord].audio);
                }, 500); // 稍微延迟一下，确保 DOM 已经更新
            }

            // 创建输入框
            for (let i = 0; i < currentWord.length; i++) {
                const inputBox = document.createElement("input");
                inputBox.type = "text";
                inputBox.maxLength = 1;
                inputBox.classList.add("letter-input");
                inputBox.dataset.index = i;
                inputContainer.appendChild(inputBox);
                
                inputBox.addEventListener("input", function(event) {
                    const input = event.target;
                    const letter = input.value.toUpperCase();
                    const index = parseInt(input.dataset.index);
                    
                    // 只允许英文字母
                    if (!/^[A-Z]$/.test(letter)) {
                        input.value = '';
                        return;
                    }

                    const correctLetter = currentWord[index].toUpperCase();
                    
                    if (letter === "") {
                        event.target.classList.remove("correct", "incorrect");
                        console.log(event.target.className); // 这应该只显示 "letter-input"

                    } else if (letter === correctLetter) {
                        event.target.classList.remove("incorrect");
                        event.target.classList.add("correct");
                        
                        if (!correctLetters[index]) {  // 只有当这个字母之前没有被正确输入过时才计分
                            correctLetters[index] = true;
                            score ++;
                            combo ++;
                           // score += 10 * combo;
                            correctAttempts++;
                            totalAttempts++;
                            displayCombo();
                        }
                        
                        if (index < currentWord.length - 1) {
                            inputContainer.children[index + 1].focus();
                        } else {
                            showCompletedWord();
                        }
                    } else {
                        event.target.classList.remove("correct");
                        event.target.classList.add("incorrect");
                        combo = 0;
                        score -= 2;
                        totalAttempts++;
                    }
                    completionRate = (completedWords / words.length).toFixed(2);
                    scoreDisplay.innerText = `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
                    
                    //displayCombo();
                });

                // 修改键盘操作事件监听器
                inputBox.addEventListener("keydown", function(event) {
                    const index = parseInt(event.target.dataset.index);
                    if (event.key === "Backspace") {
                        //回退combo清零
                        combo = 0;

                        if (event.target.value === "" && index > 0) {
                            const previousInput = inputContainer.children[index - 1];
                            previousInput.focus();
                            // 重置前个输入框的样式
                            previousInput.value = '';
                            previousInput.classList.remove("correct", "incorrect");
                            
                        } else {
                            // 处理删除操作
                            event.preventDefault(); // 阻止默认行为
                            event.target.value = '';
                            event.target.classList.remove("correct", "incorrect");

                        }

                    } else if (event.key === "ArrowLeft" && index > 0) {
                        inputContainer.children[index - 1].focus();
                    } else if (event.key === "ArrowRight" && index < currentWord.length - 1) {
                        inputContainer.children[index + 1].focus();
                    }
                });

                // 聚焦效果
                inputBox.addEventListener("focus", function(event) {
                    event.target.classList.add("focused");
                });

                inputBox.addEventListener("blur", function(event) {
                    event.target.classList.remove("focused");
                });
            }

            inputContainer.children[0].focus();

            // Add event listener for the skip button
            const skipButton = document.getElementById('skip-button');
            skipButton.addEventListener('click', skipWord);
        }

        function showCompletedWord() {
            inputContainer.innerHTML = "";
            const completedWordDisplay = document.createElement("div");
            completedWordDisplay.textContent = currentWord;
            completedWordDisplay.classList.add("completed-word");
            inputContainer.appendChild(completedWordDisplay);

            // Mark the word as completed and increment the completedWords counter
            wordResults[currentWord] = true;
            completedWords++;
            
            setTimeout(() => {
                wordIndex++;
                initializeWord();
            }, 1500);
        }

        // 初始化第一个单词
        initializeWord();

        function displayCombo() {
            if (combo > 1) {
                comboDisplay.style.animation = 'none';
                comboDisplay.offsetHeight; // Trigger reflow
                comboDisplay.style.animation = null;
                comboDisplay.classList.add('combo-visible');
                comboDisplay.innerText = `Combo x${combo}`;
                comboDisplay.style.animation = 'comboAnimation 0.7s ease-in-out';
                comboDisplay.classList.remove('combo-visible');
            } else {
                comboDisplay.classList.remove('combo-visible');
            }
            
           
        }

        const FULL_DASH_ARRAY = 283;
        const WARNING_THRESHOLD = 30;
        const ALERT_THRESHOLD = 10;

        const COLOR_CODES = {
            info: {
                color: "green"
            },
            warning: {
                color: "orange",
                threshold: WARNING_THRESHOLD
            },
            alert: {
                color: "red",
                threshold: ALERT_THRESHOLD
            }
        };

        let timePassed = 0;
        let timeLeft = timerDuration;
        let timerInterval = null;

        function formatTime(time) {
            const minutes = Math.floor(time / 60);
            let seconds = time % 60;
            if (seconds < 10) {
                seconds = `0${seconds}`;
            }
            return `${minutes}:${seconds}`;
        }

        function setRemainingPathColor(timeLeft) {
            const { alert, warning, info } = COLOR_CODES;
            if (timeLeft <= alert.threshold) {
                document.getElementById("base-timer-path-remaining").classList.remove(warning.color);
                document.getElementById("base-timer-path-remaining").classList.add(alert.color);
            } else if (timeLeft <= warning.threshold) {
                document.getElementById("base-timer-path-remaining").classList.remove(info.color);
                document.getElementById("base-timer-path-remaining").classList.add(warning.color);
            }
        }

        function calculateTimeFraction() {
            const rawTimeFraction = timeLeft / timerDuration;
            return rawTimeFraction - (1 / timerDuration) * (1 - rawTimeFraction);
        }

        function setCircleDasharray() {
            const percentage = calculateTimeFraction() * 100;
            document
                .getElementById("base-timer-path-remaining")
                .setAttribute("x2", percentage);
        }

        function startTimer() {
            timerInterval = setInterval(() => {
                timePassed = timePassed += 1;
                timeLeft = timerDuration - timePassed;
                document.getElementById("base-timer-label").innerHTML = formatTime(timeLeft);
                setCircleDasharray();
                setRemainingPathColor(timeLeft);

                if (timeLeft === 0) {
                    clearInterval(timerInterval);
                    endGame();
                }
            }, 1000);
        }

        function endGame() {
            // 立即停止倒数
            clearInterval(timerInterval);

            

            // 禁止输入
            const inputs = document.querySelectorAll('.letter-input');
            inputs.forEach(input => {
                input.disabled = true;
            });

            // Display "TIME'S UP!" or show completion image based on the condition
            const timesUpElement = document.getElementById('times-up');
            const completionImage = document.getElementById('completion-image');
            if (completedWords >= words.length) {
                showCompletionImage();
            } else if (timeLeft === 0)  {
                if (completionRate >= 0.5) {
                    timesUpElement.textContent = "TIME'S UP!";
                    timesUpElement.style.color = '#FFC107'; // Amber color
                } else {
                    timesUpElement.textContent = "TIME'S UP!";
                    timesUpElement.style.color = '#F44336'; // Red color
                }
                timesUpElement.classList.add('show');
            }

            // Update completionRate calculation
            completionRate = (completedWords / words.length).toFixed(2);

            // 发送游戏结果到服务器
            fetch('/submit_game_result', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    game_id: game_id,
                    score: score,
                    completion_rate: completionRate
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Game result submitted:', data);
                // 可以在这里添加一些用户反馈，比如显示一个消息说结果已保存
            })
            .catch((error) => {
                console.error('Error:', error);
            });

            // 显示单词列表
            showWordList();

            // 3秒后隐藏 "GAME OVER!" 并显示最终得分
            // setTimeout(() => {
            //     timesUpElement.classList.remove('show');
            //     showFinalScore();
            // }, 3000);
        }

        function showCompletionImage() {
            const completionImage = document.getElementById('completion-image');
            completionImage.style.backgroundImage = "url('{{ url_for('static', filename='completed.png') }}')";
            completionImage.classList.add('show');

            // Trigger the animation
            setTimeout(() => {
                completionImage.classList.add('animate');
            }, 50);
        }

        // function showFinalScore() {
        //     const finalScoreElement = document.getElementById('final-score');
        //     // finalScoreElement.textContent = `最终得分: ${score}`;
        //     // finalScoreElement.classList.add('show');
        // }

        function showWordList() {
            const wordlistContainer = document.getElementById('wordlist-container');
            const wordResultsList = document.getElementById('word-results');
            
            wordlistContainer.style.display = 'block';
            wordResultsList.innerHTML = '';

            words.forEach(word => {
                const listItem = document.createElement('li');
                const wordSpan = document.createElement('span');
                const iconSpan = document.createElement('span');
                
                wordSpan.textContent = word;
                
                iconSpan.className = 'word-result-icon';
                if (wordResults[word]) {
                    iconSpan.className += ' correct';
                    iconSpan.innerHTML = '&#10004;'; // Checkmark
                } else {
                    iconSpan.className += ' incorrect';
                    iconSpan.innerHTML = '&#10008;'; // Cross
                }
                
                listItem.appendChild(wordSpan);
                listItem.appendChild(iconSpan);
                wordResultsList.appendChild(listItem);
            });
        }

        document.getElementById("timer").innerHTML = `
        <div class="base-timer">
          <svg class="base-timer__svg" viewBox="0 0 100 10" xmlns="http://www.w3.org/2000/svg">
            <g class="base-timer__circle">
              <line class="base-timer__path-elapsed" x1="0" y1="5" x2="100" y2="5" />
              <line
                id="base-timer-path-remaining"
                class="base-timer__path-remaining ${COLOR_CODES.info.color}"
                x1="0" y1="5" x2="100" y2="5"
              />
            </g>
          </svg>
          <span id="base-timer-label" class="base-timer__label">${formatTime(timeLeft)}</span>
        </div>
        `;

        // Remove the startTimer() call from here

        // 在 <head> 标签添加 Orbitron 字体
        const link = document.createElement('link');
        link.href = 'https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap';
        link.rel = 'stylesheet';
        document.head.appendChild(link);

        // Add the skipWord function
        function skipWord() {
            combo = 0;
            displayCombo();
            wordResults[currentWord] = false; // 将跳过的单词标记为未完成
            showSkippedWord();
        }

        function showSkippedWord() {
            inputContainer.innerHTML = "";
            const skippedWordDisplay = document.createElement("div");
            skippedWordDisplay.textContent = currentWord;
            skippedWordDisplay.classList.add("completed-word");
            inputContainer.appendChild(skippedWordDisplay);

            setTimeout(() => {
                wordIndex++;
                initializeWord();
            }, 2000);
        }

        // 保留原来的 playAudio 函数，用于点击播放
        function playAudio(audioUrl, iconElement) {
            console.log("audio-url", audioUrl);
            if (audioUrl) {
                const audio = new Audio(audioUrl);
                
                iconElement.classList.add('playing');
                
                audio.play().catch(error => console.log("Playback prevented:", error));
                
                audio.onended = function() {
                    iconElement.classList.remove('playing');
                };
            }
        }

        // 新增：开始游戏的函数
        function startGame() {
            autoPlayEnabled = true;
            document.getElementById('start-game-button').style.display = 'none';
            document.getElementById('blur-overlay').style.opacity = '0';
            setTimeout(() => {
                document.getElementById('blur-overlay').style.display = 'none';
            }, 300); // 等待淡出动画完成后隐藏元素
            initializeWord();
            startTimer(); // Add this line to start the timer when the game starts
        }
    </script>
</body>
</html>